const fs = require("fs-extra");
const path = require("path");
const DEF_SIZE = 1024 * 1024 * 100;
const TEMP_DIR = path.resolve(__dirname, "../public", "uploads");
const PUB_DIR = path.resolve(__dirname, "../public", "uploads");

const pipeStream = (filePath, ws) => {
  return new Promise((resolve, reject) => {
    let rs = fs.createReadStream(filePath);
    rs.on("end", async () => {
      await fs.unlink(filePath);
      resolve();
    });
    rs.pipe(ws);
  });
};

// 合并分割后的文件
const mergeChunks = async (fileName, size = DEF_SIZE) => {
  const filePath = path.resolve(PUB_DIR, fileName);
  const chunksDir = path.resolve(TEMP_DIR, fileName);
  try {
    const chunkFiles = await fs.readdir(chunksDir);
    // 文件名进行排序
    chunkFiles.sort((a, b) => {
      return Number(a.split("-")[1]) - Number(b.split("-")[1]);
    });
    await Promise.all(
      chunkFiles.map((chunkFile, index) => {
        return pipeStream(
          path.resolve(chunksDir, chunkFile),
          fs.createWriteStream(filePath, {
            start: index * size,
          })
        );
      })
    );
    await fs.rmdir(chunksDir);
  } catch (e) {
    console.error(e, "*****************");
  }
};
// mergeChunks('vue3.png');
module.exports = {
  TEMP_DIR,
  PUB_DIR,
  mergeChunks,
};
